import Vue from 'vue';
import VueRouter from 'vue-router';
import HomeView from '../views/HomeView.vue';
import LoginView from '../views/LoginView.vue';
import PublicActivitiesView from '../views/PublicActivitiesView.vue';
import ActivityManagementView from '../views/ActivityManagementView.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/public-activities',
    name: 'public-activities',
    component: PublicActivitiesView,
    meta: { requiresAuth: true }
  },
  {
    path: '/public-activities/:id',
    name: 'activity-detail',
    component: () => import('../views/ActivityDetailView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/activity-management',
    name: 'activity-management',
    component: ActivityManagementView,
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  {
    path: '/user',
    name: 'user',
    component: () => import('../views/UserView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/create-activity',
    name: 'create-activity',
    component: () => import('../views/CreateActivityView.vue'),
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  {
    path: '/edit-activity/:id',
    name: 'edit-activity',
    component: () => import('../views/EditActivityView.vue'),
    meta: { requiresAuth: true, requiresAdmin: true }
  }
];

const router = new VueRouter({
  routes
});

// 全局前置路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = !!localStorage.getItem('role');
  if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
    next('/login');
  } else if (to.matched.some(record => record.meta.requiresAdmin) && localStorage.getItem('role') !== 'admin') {
    alert('无权限访问');
    next('/');
  } else {
    next();
  }
});

export default router;